<template>
	<el-dropdown trigger="click">
		<div class="user-avatar-info flex items-center pl-3 pr-3 mt-1 mb-1">
			<div class="flex-col username pr-1 text-right leading-4">
				<div class="text-base">{{ userInfo.alias || userInfo.username }}</div>
				<div class="text-sm text-gray-500 truncate" style="max-width: 230px">{{ userInfo.roleName }}</div>
			</div>
			<div class="flex-col avatar p-1">
				<img :src="userInfo.avatar ? filePrefix() + userInfo.avatar : defaultImg" alt="avatar" />
			</div>
		</div>
		<template #dropdown>
			<el-dropdown-menu>
				<el-dropdown-item @click="gotoProfile">
					<i class="iconfont iconbx-user pr-2" />{{ $t("header.personalData") }}
				</el-dropdown-item>
				<!-- <el-dropdown-item @click="openDialog('passwordRef')">
					<span class="iconfont iconedit-3" />{{ $t("header.changePassword") }}
				</el-dropdown-item> -->
				<el-dropdown-item @click="logout" divided>
					<i class="iconfont iconarrow-down-right-1 pr-2" />{{ $t("header.logout") }}
				</el-dropdown-item>
			</el-dropdown-menu>
		</template>
	</el-dropdown>
</template>

<script setup lang="ts">
import { logoutApi } from "@/api/modules/login";
import defaultImg from "@/assets/images/user.png";
import { LOGIN_URL } from "@/config/config";
import { filePrefix } from "@/hooks/useSystem";
import { AuthStore } from "@/stores/modules/auth";
import { PublicStore } from "@/stores/modules/public";
import { ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { ComponentInternalInstance, getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const publicStore = PublicStore();
const userInfo: User.UserInfo = publicStore.userInfo;

// 退出登录
const logout = () => {
	ElMessageBox.confirm(proxy?.$t("loginout.elmsg.confirm"), proxy?.$t("loginout.elmsg.title"), {
		confirmButtonText: proxy?.$t("loginout.elmsg_btn.confirm"),
		cancelButtonText: proxy?.$t("loginout.elmsg_btn.cancel"),
		type: "warning"
	}).then(async () => {
		const authStore = AuthStore();
		authStore.setDeptList([]);
		// 1.调用退出登录接口
		await logoutApi();
		// 2.清除 Token
		publicStore.setToken("");
		// 3.重定向到登陆页
		router.replace(LOGIN_URL);
	});
};
const gotoProfile = () => {
	router.push("/user/profile");
};

// // 打开修改密码和个人信息弹窗
// const openDialog = (refName: string) => {
// 	if (refName == "infoRef") infoRef.value?.openDialog();
// 	else passwordRef.value?.openDialog();
// };
</script>

<style scoped lang="scss">
.user-avatar-info {
	cursor: pointer;
}
.user-avatar-info:hover {
	background: var(--el-color-primary-light-9);
}
.avatar {
	width: 40px;
	height: 40px;
	overflow: hidden;
	img {
		width: 100%;
		height: 100%;
	}
}
</style>
